<?php

namespace app\agent\service;

use app\api\service\CommonService;
use app\model\Agent;
use app\model\AgentChannel;
use app\model\AgentServiceConfig;
use app\model\ChannelServDiscount;
use app\model\Template;
use app\model\TemplateService;
use think\facade\Db;

class Channel extends CommonService
{
    // 保存渠道
    public function channelSave($param, $config, $agentId, $id = 0)
    {
        // step 校验业务权限
        $templateInfo = Template::find($param['template_id']);
        if (!$templateInfo) {
            return $this->inValiReturn('模板已被删除，请重新选择');
        }

        /*
        step   模板权限  业务权限  折扣取值设置合法性校验
        1，渠道设置的折扣不能低于 平台给代理商的折扣
        2，费业务单独处理 ，其余的从 AgentServiceConfig 获取
        */
        $templateServ = TemplateService::where('template_id', $param['template_id'])->column('serv_type', 'serv_type');
        if (!$templateServ) {
            return $this->inValiReturn('该模板尚未配置任何业务');
        }
        $agentServ = AgentServiceConfig::where('status', 1)->where('agent_id', $agentId)->column('*', 'serv_type');
        if (!$agentServ) {
            return $this->inValiReturn('代理商没有开通任何业务');
        }
        $agentInfo = Agent::find($agentId);

        $param['state'] = 2;
        $hasMobile = false;
        $mobileFastState = 0;
        $mobileSlowState = 0;
        foreach ($config as $k => $v) {
            if (isset($v['state']) && $v['state'] == 1) {
                $param['state'] = 1;
            }
            // step 模板权限
            if (!isset($templateServ[$v['serv_type']])) {
                return $this->inValiReturn('模板没有【' . PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '】权限');
            }
            if (empty($agentServ[$v['serv_type']])) continue;
            // step 代理商业务权限
            if (!isset($agentServ[$v['serv_type']]) && $v['state'] != 2) {

                $product_name = !empty(PRODUCT_SERV_TYPE[$v['serv_type']])?PRODUCT_SERV_TYPE[$v['serv_type']]['name']:'外卖';

                return $this->inValiReturn("请禁用未开通产品：".$product_name,500,'');
            }
//            if (!isset($v['value'])){
//                continue;
//            }

            // 话费，电费，油卡
            if (isset($v['value']) && in_array($v['serv_type'], [PRODUCT_MOBILE_SERV, PRODUCT_POWER_SERV, PRODUCT_OILCARD_SERV])) {
                if ($v['value'] < 90 || $v['value'] > 130) {
                    $rechargeType = SLOW_RECHARGE == $v['sub_type'] ? '慢充' : '快充';
                    return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . $rechargeType . '折扣范围：90.00 ~ 130.00');
                }
            }

            // step 折扣不能低于 平台给代理商的折扣
            if (PRODUCT_MOBILE_SERV == $v['serv_type']) { // 话费业务
                $hasMobile = true;
                if (SLOW_RECHARGE == $v['sub_type']) {
                    // 返佣的才需要判断折扣[agent_lower_price != 1 的也要判断]
                    if (($agentInfo->settle_type == 1 || $agentServ[$v['serv_type']]['agent_lower_price'] != 1) && $v['value'] < $agentInfo->mobile_discount_slow) {
                        return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '慢充折扣不能低于' . $agentInfo->mobile_discount_slow);
                    }
                    $mobileSlowState = $v['state'];
                } else {
                    // 返佣的才需要判断折扣
                    if (($agentInfo->settle_type == 1 || $agentServ[$v['serv_type']]['agent_lower_price'] != 1) && $v['value'] < $agentInfo->mobile_discount_fast) {
                        return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '快充折扣不能低于' . $agentInfo->mobile_discount_fast);
                    }
                    $mobileFastState = $v['state'];
                }
            } else {
                // 影票，权益卡，外卖 不需要设置折扣
                //增加 周边游、出行不需要折扣
                if ($agentInfo->settle_type == 1 && 3 != $v['sub_type'] && !in_array($v['serv_type'], [
                        PRODUCT_COUPON_SERV,
                        PRODUCT_FILM_SERV,
                        PRODUCT_TRAVEL_OIL_SERV,
                        PRODUCT_AROUND_SHOP_SERV,
                        PRODUCT_FOOD_SHOP_SERV,
                        PRODUCT_SECKILL_SERV,
                        PRODUCT_ELE_SERV,
                        PRODUCT_MEITUAN_TAKEOUT_SERV,
                        PRODUCT_METUAN_SERV,
                        PRODUCT_MOBILE_CPS_SERV,
                    ])) { // 设置折扣合法性(3表示不需要设置折扣的业务)
                    if (SLOW_RECHARGE == $v['sub_type']) {
                        if ($v['value'] < $agentServ[$v['serv_type']]['discount_slow']) {
                            return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '慢充折扣不能低于' . $agentServ[$v['serv_type']]['discount_slow']);
                        }
                    } elseif (FAST_RECHARGE == $v['sub_type']) {
                        if ($v['value'] < $agentServ[$v['serv_type']]['discount_fast']) {
                            return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '快充折扣不能低于' . $agentServ[$v['serv_type']]['discount_fast']);
                        }
                    } else {
                        if ($v['value'] < $agentServ[$v['serv_type']]['value']) {
                            return $this->inValiReturn(PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '折扣不能低于' . $agentServ[$v['serv_type']]['value']);
                        }
                    }
                }
            }
        }
        if ($hasMobile) {
            if ($mobileFastState != 1 && $mobileSlowState != 1) {
                return $this->inValiReturn('话费慢充快充不能同时禁用');
            }
        }

        if ($id) {
            $model = AgentChannel::where('agent_id', $agentId)->find($id);
            if (!$model) {
                return $this->inValiReturn('渠道不存在，请刷新');
            }
        } else {
            $param['agent_id'] = $agentId;
            $model = new AgentChannel();
        }

        Db::startTrans();
        try {
            // 清除配置
            if ($id) {
                ChannelServDiscount::where('channel_id', $id)->delete();
            } else {
                Db::name('template')
                    ->where('id', $param['template_id'])
                    ->inc('use_num', 1)
                    ->update();
            }
            $res = $model->save($param);
            $res = $model->servDiscount()->saveAll(array_values($config));
            if (!$res) {
                Db::rollback();

                return $this->inValiReturn('渠道保存失败,请重试或者联系我们');
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            doLog(getExceptionMsg($e));

            return $this->inValiReturn('渠道保存失败,请重试或者联系我们');
        }

        return $this->valiReturn();
    }
}
